﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Printing;
using System.Windows.Threading;
using NetBay.Core.Silverlight.Extensions;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.Helpers;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Enums;
using Rio.Framework.Pages.Events;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Helpers.Utils;
using Rio.Framework.Pages.Manager;
using Rio.Framework.WCFService;
using Rio.Framework.WCFService.RioWcfServices;
using Telerik.Windows.Controls.DragDrop;
using Telerik.Windows.Controls.TreeView;
using Document = NetBay.Core.BusinessEntities.Document;
using VersioningItem = NetBay.Core.BusinessEntities.Versioning.VersioningItem;
using Rio.Framework.Pages.AppCode.Enums;
using System.Net;
using Rio.Framework.Pages.ChildWindows;

#endregion

namespace Rio.Framework.Pages.Viewer
{
    public class UCViewerCore : ControlBase
    {
        #region Enums
        public enum ClickEvent
        {
            FirstPageClick,
            PreviousPageClick,
            NextPageClick,
            LastPageClick,
            FirstDocumentClick,
            PreviousDocumentClick,
            NextDocumentClick,
            LastDocumentClick,
            SaveModificationClick,
            ListBoxItemChange,
            SaveModification,
            Viewer,
            ItemDisplay,
            OpenDirectory,
            ReturnDirectory,
            List
        }
        #endregion

        #region Attributs
        protected SaveFileDialog _saveFileDialog;

        protected bool _IsViewerInitialized = false;

        protected bool _isToolBarMinimized = true;
        private List<string> _listAllDocFileName = new List<string>();

        protected List<ImageRio> _selectedImages;

        /// <summary>
        /// Contains all Images get with Wcf
        /// </summary>
        public ObservableCollection<ImageRio> m_oItemsSource { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected NetBay.Core.BusinessEntities.Folder m_oFolder;

        /// <summary>
        /// List of Documents (from ListVignetteSearch)
        /// </summary>
        public List<Document> m_oListDocument = new List<Document>();

        /// <summary>
        /// 
        /// </summary>
        protected int m_iSelectedViewerDocIndex = -1;

        ///// <summary>
        ///// The current collection of ImageRio to delete (ONLY the image file are in this Collection)
        ///// </summary>
        //private ObservableCollection<ImageRio> m_oFilesToDelete;

        protected NetBay.Core.BusinessEntities.Organization m_oCurrentOrganization;

        protected NetBay.Core.BusinessEntities.FolderType m_oCurrentFolderType;

        /// <summary>
        /// 
        /// </summary>
        private IList m_oFilesToConvert;

        /// <summary>
        /// 
        /// </summary>
        protected bool m_bReloadThumbnail = true;

        /// <summary>
        /// This field is used to store the list of filename of document to convert though WF Service (ConvertDocumentAppend)
        /// </summary>
        private List<string> m_oFilenamesToConvert = new List<string>();

        /// <summary>
        /// This field is used to navigate in list of document to convert
        /// </summary>
        private int m_iCurrentIndextoFilenamesToConvert = 0;

        /// <summary>
        /// This field is used to initialize a documents convert. At each conerting, a new guid is generated.
        /// </summary>
        private Guid m_oGuidSessionToConvert;

        protected ConsultationModeType ConsultationMode;

        protected string versionRelativeFilepath;

        protected VersioningItem displayedVersion;

        protected VersioningManager _versioningManager;

        #endregion

        #region Properties

        public virtual bool ScanImportIsEnabled { get; set; }

        /// <summary>
        /// Gets or sets the save modification enabled.
        /// </summary>
        /// <value>The save modification enabled.</value>
        public bool SaveModificationEnabled
        {
            get
            {
                if (ModifyRotateList != null && ModifyRotateList.Count > 0)
                    return true;
                else
                    return false;
            }
        }

        /// <summary>
        /// List of documents (from ListVignetteSearch)
        /// </summary>
        public List<Document> ListDocument
        {
            get { return m_oListDocument; }
            set
            {
                m_oListDocument = value;
                OnListDocumentUpdated();
            }
        }

        /// <summary>
        /// Root of storage
        /// </summary>
        public string ParameterStorage
        {
            get
            {
                return GlobalWebContext.ParameterStorage;
            }
        }

        #region Labels
        // Prompt this message for user when image or thumbnail is modify
        protected string LabelSaveModificationImage { get; set; }
        // Prompt this message for user when the merge into pdf format was in error
        protected string LabelMergePDFFormatFileError { get; set; }
        // Prompt this message for user when thumbnail will be deleted
        protected string LabelDeleteThumbnail { get; set; }
        // Prompt this message for user when a merge pdf operation is requested
        protected string LabelMergePdfQuestion { get; set; }
        // Prompt this message for user when they have selected unsupported file for the rotation
        protected string LabelRotateUnsupportedFile { get; set; }
        #endregion

        /// <summary>
        ///  List of rotation by page of document
        /// </summary>
        protected Dictionary<string, Dictionary<int, RotateFlipType>> ModifyRotateList { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected PrintDocument PrintDocument { get; set; }

        /// <summary>
        /// User Id
        /// </summary>
        public long UserId { get; set; }

        /// <summary>
        /// List of all documents file name
        /// </summary>
        public List<string> ListAllDocFileName
        {
            get { return _listAllDocFileName; }
            set { _listAllDocFileName = value; }
        }

        /// <summary>
        /// Selected index of the thumbnail 
        /// </summary>
        public int SelectedDocumentIndex { get; set; }

        /// <summary>
        /// Root of storage of thumbnail
        /// </summary>
        protected string ParameterStorageThumbnail
        {
            get
            {
                return GlobalWebContext.ParameterStorageThumbnail;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public List<string> RankedListFromViewer { get; set; }

        /// <summary>
        /// Gets or sets the ranked list of image from viewer.
        /// </summary>
        /// <value>
        /// The ranked list of image from viewer.
        /// </value>
        public List<ImageRio> RankedListOfImageFromViewer { get; set; }

        /// <summary>
        /// SearchMode
        /// </summary>
        public AppDisplayMode CurrentDisplayMode { get; set; }

        /// <summary>
        /// Gets or sets the selected images.
        /// </summary>
        /// <value>The selected images.</value>
        public List<ImageRio> SelectedImages
        {
            get
            {
                return _selectedImages;
            }
            set
            {
                _selectedImages = value;
                UpdateSelectImages();
            }
        }

        #endregion

        #region Virtual

        /// <summary>
        /// Used to get or set the current ImageRio
        /// </summary>
        public virtual ImageRio CurrentSelectedImage { get; set; }

        /// <summary>
        /// Get or set a list of all thumbnail
        /// </summary>
        public virtual IList<ImageRio> RioImageList { get; set; }

        /// <summary>
        /// Return the file name selected
        /// </summary>
        protected virtual string GetFileNameSelected { get; set; }

        /// <summary>
        /// Used to save the current Directory name
        /// </summary>
        public virtual string CurrentSelectedDirectory { get; set; }

        /// <summary>
        /// Updates the select images.
        /// </summary>
        public virtual void UpdateSelectImages() { }

        /// <summary>
        /// Manages the state of the toolbar.
        /// </summary>
        public virtual void ManageToolbarState() { }

        /// <summary>
        /// Changes the consultation mode.
        /// </summary>
        /// <param name="organization">The organization.</param>
        /// <param name="folderType">Type of the folder.</param>
        /// <param name="modeToApply">The mode to apply.</param>
        /// <param name="isVersioningActivated">if set to <c>true</c> [is versioning activated].</param>
        public virtual void ChangeConsultationMode(NetBay.Core.BusinessEntities.Organization organization, NetBay.Core.BusinessEntities.FolderType folderType, ConsultationModeType modeToApply, bool isVersioningActivated = false)
        { }

        #endregion

        #region Delegates
        // Define a delegate named RefreshHandler, which will encapsulate
        public delegate void FileNameSelectedHandler(object sender, DocumentSelectedEventArgs args);
        public delegate void DocumentsDeletedHandler(List<Document> p_oListDocument);
        protected delegate void RefreshSourceDocumentHandler(Byte[] p_aRawImage, int p_iIndexDocumentSelected, int p_iNbOfPage);
        public delegate void ImportedDocumentDeletedHandler(ImageRio p_oImageRioDeleted);
        public delegate void ImportedDocumentRefreshedHandler(ObservableCollection<ImageRio> p_oImageRioCollection);
        public delegate void ImportDocumentProgressedHandler(ObservableCollection<ImageRio> p_oImageRioCollection);
        public delegate void ItemsLoadedHandler(object sender, DocumentSelectedEventArgs args);
        #endregion

        #region Events
        public event EventHandler AddDocumentEvent;
        /// Event raised when the documents has been deleted
        public event DocumentsDeletedHandler ItemsDeletedToRemove;
        /// Event raised when the documents has been doubleclicked to display
        public event DocumentSelectedHandler ItemsSelectedToDisplay;
        /// Event raised when the documents has been doubleclicked to display
        public event DocumentSelectedHandler ItemsSelectedDocument;
        /// Event raisen when a directory has been doubleclicked to display
        public event DirectorySelectedHandler DirectorySelectedToDisplay;
        /// Event raisen when a directory has been doubleclicked to display
        public event DirectorySelectedHandler DirectorySelected;
        /// Event raised when the documents has been selected
        public event FileNameSelectedHandler ItemsSelectedFileName;
        //Event raised when the imported document has been deleted
        public event ImportedDocumentDeletedHandler ImportedDocumentDeleted;
        //Event raised when the imported documents has been refreshed
        public event ImportedDocumentRefreshedHandler ImportedDocumentRefreshed;
        //Event raised when the the import of document progress
        public event ImportDocumentProgressedHandler ImportDocumentProgressed;
        //Event raised when the imported documents has been merged and an error has occured
        public event EventHandler ImportedDocumentMergedFailed;
        //Event raised when the documents has been loaded
        public event ItemsLoadedHandler ItemsLoaded;
        //Event raised when the user must refresh the thumbnails
        public event EventHandler RefreshThumbnails;
        //Event raised when the user click on the viewer mode
        public event EventHandler ActivateViewerMode;
        //Event raised when the user click on the thumbnail mode
        public event EventHandler ActivateThumbnailMode;
        //Event raised when the user click on the list mode
        public event EventHandler ActivateListMode;
        //Event raised when the initialization of this class is ok
        public event EventHandler InitialisationCompleted;
        //Event raised when the list of document are updated
        public event EventHandler ListDocumentUpdated;
        //Event raised when a image have been displayed
        public event EventHandler DisplayCompleted;
        //Event raised when the file import is finished 
        public event EventHandler EndOfImport;
        //Event raised when the toolbar changed
        public event EventHandler ToolbarStateHasChanged;
        //Event raised when the paste menu is clicked
        public event PasteCopyEventHandler CopyPasteDocuments;
        //Event raised before copying files
        public event PasteCopyEventHandler BeforeCopyPasteDocuments;
        //Event raised when the paste menu is clicked
        public event EventHandler BeforeIndexFiles;
        //Event raised when the Import is clicked
        public event EventHandler ImportRequest;
        //Event raised when the Import is clicked
        public event EventHandler ScanRequest;
        public event VersioningEventHandler NewVersionAdded;

        #endregion

        #region Constructor

        public UCViewerCore()
            : this(null, AppDisplayMode.None)
        {
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public UCViewerCore(List<Document> p_oListDocument = null, AppDisplayMode p_oDisplayMode = AppDisplayMode.None)
        {
            // Initialize the Search mode 
            CurrentDisplayMode = p_oDisplayMode;

            // Initialize the dictionary af all status of image rotation
            ModifyRotateList = new Dictionary<string, Dictionary<int, RotateFlipType>>();
            m_oListDocument = p_oListDocument;

            ScanImportIsEnabled = true;

            this._saveFileDialog = new SaveFileDialog();

            //Versioning manager 
            _versioningManager = new VersioningManager();
            _versioningManager.VersionCreated += _versioningManager_VersionCreated;
            _versioningManager.CreationError += _versioningManager_CreationError;

            try
            {
                this._saveFileDialog.DefaultExt = ".txt";
                this._saveFileDialog.Filter = "All Files|*.*";
                this._saveFileDialog.FilterIndex = 1;
            }
            catch (Exception ex)
            {
                LoggerHelper.Send(this.GetType().Name, "CheckOutClick EXCEPTION : " + Environment.NewLine + ex.Message);
            }
        }

        void _versioningManager_CreationError(object sender, VersioningEventArgs args)
        {
            throw new NotImplementedException();
        }

        void _versioningManager_VersionCreated(object sender, VersioningEventArgs args)
        {
            OnNewVersionAdded(args);
        }

        #endregion

        #region OnEvents

        /// <summary>
        /// Called when [importing].
        /// </summary>
        protected virtual void OnImportRequest()
        {
            if (ImportRequest != null)
                ImportRequest(this, EventArgs.Empty);
        }

        /// <summary>
        /// Called when [scan request].
        /// </summary>
        protected virtual void OnScanRequest()
        {
            if (ScanRequest != null)
                ScanRequest(this, EventArgs.Empty);
        }

        /// <summary>
        /// Called when [scan request].
        /// </summary>
        protected virtual void OnNewVersionAdded(VersioningEventArgs args)
        {
            if (NewVersionAdded != null)
                NewVersionAdded(this, args);
        }

        /// <summary>
        /// Protected method to raise the event 'AddDocumentEvent'
        /// </summary>
        protected virtual void OnAddDocumentEvent()
        {
            if (AddDocumentEvent != null)
                AddDocumentEvent(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'ItemsDeletedToRemove'
        /// </summary>
        /// <param name="p_oListItemDeleted">List of selected Document</param>
        protected void OnItemsDeletedToRemove(List<Document> p_oListItemDeleted)
        {
            if (ItemsDeletedToRemove != null)
                ItemsDeletedToRemove(p_oListItemDeleted);

        }

        /// <summary>
        /// Protected method for raise the event 'ItemsDeleteImportDocumentProgresseddToRemove'
        /// </summary>
        /// <param name="p_oImageRioCollection">The p_o image rio collection.</param>
        protected void OnImportDocumentProgressed(ObservableCollection<ImageRio> p_oImageRioCollection)
        {
            if (ImportDocumentProgressed != null)
                ImportDocumentProgressed(p_oImageRioCollection);
        }

        /// <summary>
        /// Protected method for raise the event 'ItemsSelectedToDisplay'
        /// </summary>
        /// <param name="p_oListItem">List of selected Document</param>
        protected void OnItemsSelectedToDisplay(List<Document> p_oListItem)
        {
            if (ItemsSelectedToDisplay != null)
                ItemsSelectedToDisplay(this, new DocumentSelectedEventArgs
                                                 {
                                                     p_oListDocument = p_oListItem,
                                                     ListAllRioImages = m_oItemsSource,
                                                     SelectedDocumentIndex = SelectedDocumentIndex,
                                                     SelectedImage = CurrentSelectedImage,
                                                     ListAllFileName = ListAllDocFileName
                                                 });
        }

        /// <summary>
        /// Protected method for raise the event 'OnDirectorySelectedToDisplay'
        /// </summary>
        /// <param name="mode">The mode.</param>
        protected void OnDirectorySelectedToDisplay(DirectorySelectedEventArgs.Mode mode)
        {
            if (DirectorySelectedToDisplay != null)
                DirectorySelectedToDisplay(this, new DirectorySelectedEventArgs(mode)
                                                {
                                                    DirectoryName = CurrentSelectedDirectory,
                                                    SelectedDirectory = CurrentSelectedImage,
                                                    ListAllRioImages = m_oItemsSource,
                                                    SelectedImage = CurrentSelectedImage,
                                                    ListAllFileName = ListAllDocFileName
                                                });
        }

        /// <summary>
        /// Protected method for raise the event 'OnDirectorySelected'
        /// </summary>
        /// <param name="p_DirectoryName"></param>
        protected void OnDirectorySelected()
        {
            if (DirectorySelected != null)
                DirectorySelected(this, new DirectorySelectedEventArgs()
                                        {
                                            DirectoryName = CurrentSelectedDirectory,
                                            SelectedDirectory = CurrentSelectedImage,
                                            ListAllRioImages = m_oItemsSource,
                                            SelectedImage = CurrentSelectedImage,
                                            ListAllFileName = ListAllDocFileName
                                        });
        }

        /// <summary>
        /// Protected method for raise the event 'OnItemsSelected'
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_oListItem">List of selected items</param>
        /// <param name="p_oImageCollection">The p_o image collection.</param>
        protected void OnItemsSelected<T>(T p_oListItem, ObservableCollection<ImageRio> p_oImageCollection = null)
        {
            if (p_oListItem is List<Document>)
            {
                OnItemsSelectedDocument(p_oListItem as List<Document>, p_oImageCollection);
            }
            else
            {
                OnItemsSelectedFileName(p_oListItem as List<string>, p_oImageCollection);
            }
        }

        /// <summary>
        /// Protected method for raise the event 'ItemSelectedToDisplay'
        /// </summary>
        /// <param name="p_oListDocument">List of selected documents</param>
        /// <param name="p_oImages">The p_o images.</param>
        private void OnItemsSelectedDocument(List<Document> p_oListDocument, ObservableCollection<ImageRio> p_oImages)
        {
            if (ItemsSelectedDocument != null)
                ItemsSelectedDocument(this, new DocumentSelectedEventArgs()
                                            {
                                                p_oListDocument = p_oListDocument,
                                                ListAllRioImages = p_oImages,
                                                SelectedDocumentIndex = SelectedDocumentIndex,
                                                SelectedImage = CurrentSelectedImage,
                                                ListAllFileName = ListAllDocFileName
                                            });
        }

        /// <summary>
        /// Protected method for raise the event 'ItemsSelected'
        /// </summary>
        /// <param name="p_oListFileName">List of selected file name</param>
        /// <param name="p_oImagesCollection">The p_o images collection.</param>
        private void OnItemsSelectedFileName(List<string> p_oListFileName, ObservableCollection<ImageRio> p_oImagesCollection = null)
        {
            if (ItemsSelectedFileName != null)
                ItemsSelectedFileName(this, new DocumentSelectedEventArgs()
                {
                    ListAllFileName = p_oListFileName,
                    ListAllRioImages = p_oImagesCollection ?? m_oItemsSource,
                    SelectedDocumentIndex = SelectedDocumentIndex,
                    SelectedImage = CurrentSelectedImage
                });
        }

        /// <summary>
        /// Protected method for raise the event 'ImportedDocumentDeleted'
        /// </summary>
        protected void OnImportedDocumentDeleted(ImageRio p_oImageRioDeleted)
        {
            if (ImportedDocumentDeleted != null)
                ImportedDocumentDeleted(p_oImageRioDeleted);
        }

        /// <summary>
        /// Protected method for raise the event 'ImportedDocumentRefreshed'
        /// </summary>
        protected void OnImportedDocumentRefreshed(ObservableCollection<ImageRio> p_oImageRioCollection)
        {
            if (ImportedDocumentRefreshed != null)
                ImportedDocumentRefreshed(p_oImageRioCollection);
        }

        /// <summary>
        /// Protected method for raise the event 'ImportedDocumentMergedFailed'
        /// </summary>
        protected void OnImportedDocumentMergedFailed()
        {
            if (ImportedDocumentMergedFailed != null)
                ImportedDocumentMergedFailed(this, EventArgs.Empty);
        }

        /// <summary>
        /// Called when [items loaded].
        /// </summary>
        /// <param name="p_oImageCollection">The p_o image collection.</param>
        /// <param name="documents">The documents.</param>
        protected void OnItemsLoaded(ObservableCollection<ImageRioSearch> p_oImageCollection, List<Document> documents = null)
        {
            if (ItemsLoaded != null)

                ItemsLoaded(this, new DocumentSelectedEventArgs()
                {
                    p_oListDocument = documents,
                    ListAllRioImagesSearch = p_oImageCollection,
                    SelectedDocumentIndex = SelectedDocumentIndex,
                    SelectedImage = CurrentSelectedImage,
                    ListAllFileName = ListAllDocFileName
                });
        }

        /// <summary>
        /// Protected method for raise the event 'UpdateThumbnailDone'
        /// </summary>
        protected void OnRefreshThumbnails()
        {
            if (RefreshThumbnails != null)
                RefreshThumbnails(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'ActivateViewerMode'
        /// </summary>
        protected void OnActivateViewerMode()
        {
            if (ActivateViewerMode != null)
                ActivateViewerMode(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'ActivateListMode'
        /// </summary>
        protected void OnActivateListMode()
        {
            if (ActivateListMode != null)
                ActivateListMode(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'ActivateThumbnailMode'
        /// </summary>
        protected void OnActivateThumbnailMode()
        {
            if (ActivateThumbnailMode != null)
                ActivateThumbnailMode(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'InitialisationCompleted'
        /// </summary>
        protected void OnInitialisationCompleted()
        {
            if (InitialisationCompleted != null)
                InitialisationCompleted(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'ListDocumentUpdated'
        /// </summary>
        protected virtual void OnListDocumentUpdated()
        {
            if (ListDocumentUpdated != null)
                ListDocumentUpdated(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method for raise the event 'DisplayCompleted'
        /// </summary>
        protected virtual void OnDisplayCompleted()
        {
            if (DisplayCompleted != null)
                DisplayCompleted(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method to raise the event 'EndOfImport'
        /// </summary>
        protected virtual void OnEndOfImport()
        {
            if (EndOfImport != null)
                EndOfImport(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method to raise the event 'OnSplitImage'
        /// </summary>
        /// <param name="p_sImageName">Name of the P_S image.</param>
        /// <param name="NumberOfSplit">The number of split.</param>
        protected void OnSplitImage(string p_sImageName, int NumberOfSplit = 2)
        {
            CursorWait(this);
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
            L_oWCFServiceClient.CarveImportFilesCompleted += L_oWCFServiceClient_CarveImportFilesCompleted;
            L_oWCFServiceClient.CarveImportFilesAsync(new ObservableCollection<String>() { p_sImageName }, CurrentSelectedDirectory, UserId, NumberOfSplit, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Protected method to raise the event 'ToolbarStateHasChanged'
        /// </summary>
        protected virtual void OnToolbarStateHasChanged()
        {
            if (ToolbarStateHasChanged != null)
                ToolbarStateHasChanged(this, EventArgs.Empty);
        }

        /// <summary>
        /// Protected method to raise the event 'PasteDocument'
        /// </summary>
        protected virtual void OnCopyPasteDocument(PasteCopyActionType action)
        {
            if (CopyPasteDocuments != null)
                CopyPasteDocuments(this, new PasteCopyEventArgs(action));
        }

        /// <summary>
        /// Called when [before copy paste document].
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="documentsIds">The documents ids.</param>
        protected virtual void OnBeforeCopyPasteDocument(PasteCopyActionType action, List<long> documentsIds)
        {
            if (BeforeCopyPasteDocuments != null)
                BeforeCopyPasteDocuments(this, new PasteCopyEventArgs(action, null, documentsIds));
        }

        #endregion

        #region Public functions

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <returns></returns>
        //public virtual List<ImageRio> GetSelectedItems()
        //{
        //    return new List<ImageRio>();
        //}

        /// <summary>
        /// Init localization
        /// </summary>
        public override void InitLabel()
        {
            base.InitLabel();
        }

        /// <summary>
        /// Gets the type of the selected image of.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public virtual List<T> GetSelectedImage<T>()
        {
            return new List<T>();
        }

        /// <summary>
        /// Sets the selected image search.
        /// </summary>
        /// <param name="images">The images.</param>
        public virtual void SetSelectedImage<T>(List<T> images)
        {
        }

        /// <summary>
        /// Sets the actually ranking list.
        /// </summary>
        public virtual void SetActuallyRankingList()
        {
        }

        #endregion

        #region Protected functions

        /// <summary>
        /// Return thumbnail path
        /// </summary>
        /// <param name="l_sThumbnailPathWithoutExtension">Thumbnail path without extension</param>
        /// <returns>thumbnailpath</returns>
        protected string AddThumbnailExtension(string l_sThumbnailPathWithoutExtension)
        {
            if (!String.IsNullOrEmpty(l_sThumbnailPathWithoutExtension))
            {
                return Path.ChangeExtension(l_sThumbnailPathWithoutExtension, Constant.ImageFileFormat.JPG.szGetDescription());
            }
            return l_sThumbnailPathWithoutExtension;
        }

        /// <summary>
        /// Prints the documents in PDF format.
        /// </summary>
        /// <param name="l_oFileName">Name of the l_o file.</param>
        public void PrintDocumentsInPDFFormat(List<string> l_oFileName)
        {
            if ((l_oFileName != null) && (l_oFileName.Count > 0))
            {
                CursorWait(this);
                SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_PREPARE_PRINT);

                //Clean and prepare objects to converting
                m_oFilenamesToConvert.Clear();
                m_iCurrentIndextoFilenamesToConvert = 0;

                //This is a new converting, so we generate a new Guid
                m_oGuidSessionToConvert = Guid.NewGuid();

                //Save List of filename
                m_oFilenamesToConvert = new List<string>(l_oFileName);

                //call WCF to prepare converting
                WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                L_oWCFServiceClient.CreateTemporaryDirectoryCompleted += L_oWCFServiceClient_CreateTemporaryDirectoryCompleted;
                L_oWCFServiceClient.CreateTemporaryDirectoryAsync(m_oGuidSessionToConvert.ToString("N"), ServiceManager.GetLicenseKey());

                /*
                 * Add print action to historic
                 */

                BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();
                var query = l_oBecDC.AddActionHistoricQuery((int)Constant.UserActions.IMPRESSION, 0, 0, null,
                                                l_oFileName.ToString(";"));
                l_oBecDC.Load(query);
            }
        }

        /// <summary>
        /// Deletes the imported documents.
        /// </summary>
        /// <param name="itemsToDelete">The items to delete.</param>
        protected void DeleteImportedDocuments(IEnumerable<ImageRio> itemsToDelete)
        {

            ObservableCollection<ImageRio> m_oFilesToDelete = new ObservableCollection<ImageRio>(itemsToDelete);

            //delete files 
            if (m_oFilesToDelete != null && m_oFilesToDelete.Count > 0)
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, LabelDeleteThumbnail, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                L_oMessage.ShowDialog();
                L_oMessage.Closed += (s, ev) =>
                {
                    if (L_oMessage.Result == MessageBoxResult.Yes)
                    {
                        //Init & Launch SplashScreen
                        SplashScreenManager.Wait(this);
                        CursorWait(this);

                        //Add deleting to historic
                        //BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();
                        //var query = l_oBecDC.AddActionHistoricQuery((int)Constant.UserActions.SUPPRESSION_IMAGE, 0, 0, null, m_oFilesToDelete.ToString(";"));
                        //l_oBecDC.Load(query);

                        //Call service with only first element
                        WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.DeleteImportImagesCompleted += L_oWCFServiceClient_DeleteImportImagesCompleted;
                        L_oWCFServiceClient.DeleteImportImagesAsync(new ObservableCollection<ImageRio>(m_oFilesToDelete), UserId, ServiceManager.GetLicenseKey(), m_oFilesToDelete);

                    }
                };
            }
        }

        /// <summary>
        /// Refreshes the imported documents.
        /// </summary>
        /// <param name="L_iSelectedViewerDocIndex">Index of the selected viewer doc.</param>
        protected void RefreshImportedDocuments(int L_iSelectedViewerDocIndex = -1)
        {
            m_iSelectedViewerDocIndex = L_iSelectedViewerDocIndex;
            GetThumbnailList(m_iSelectedViewerDocIndex, this.CurrentSelectedDirectory);
        }


        /// <summary>
        /// Save modification
        /// </summary>
        /// <param name="p_iClickEvent">The p_i click event.</param>
        /// <param name="listInSearchMode">The list in search mode.</param>
        protected void SaveModificationOnImage(ClickEvent p_iClickEvent, List<Document> listInSearchMode = null)
        {
            if (ModifyRotateList.Count != 0)
            {
                MessageBoxChildWindow l_oMessage = new MessageBoxChildWindow(String.Empty, LabelSaveModificationImage, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                l_oMessage.ShowDialog();
                l_oMessage.Closed += (s, ev) =>
                {
                    if (l_oMessage.Result == MessageBoxResult.Yes)
                    {
                        CursorWait(this);
                        WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.SaveImportRotatedImagesWithDirectoryCompleted += L_oWCFServiceClient_SaveImportRotatedImagesCompleted;
                        //L_oWCFServiceClient.SaveImportRotatedImagesAsync(ModifyRotateList, UserId, p_iClickEvent);
                        Dictionary<bool, ClickEvent> p = new Dictionary<bool, ClickEvent>();
                        p.Add(false, p_iClickEvent);

                        L_oWCFServiceClient.SaveImportRotatedImagesWithDirectoryAsync(ModifyRotateList, UserId, CurrentSelectedDirectory, ServiceManager.GetLicenseKey(), p);

                    }
                    else
                    {
                        //Action to process immediatly and whatever the user choice
                        switch (p_iClickEvent)
                        {
                            case ClickEvent.ListBoxItemChange:
                                if (listInSearchMode == null)
                                {
                                    OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                                }
                                else
                                {
                                    OnItemsSelectedToDisplay(listInSearchMode);
                                }
                                ModifyRotateList.Clear();
                                break;
                            case ClickEvent.ItemDisplay:
                                if (listInSearchMode == null)
                                {
                                    OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                                }
                                else
                                {
                                    OnItemsSelectedToDisplay(listInSearchMode);
                                }
                                ModifyRotateList.Clear();
                                break;
                            case ClickEvent.SaveModification:
                                ModifyRotateList.Clear();
                                break;
                            case ClickEvent.Viewer:
                                ModifyRotateList.Clear();
                                OnActivateViewerMode();
                                break;
                            case ClickEvent.OpenDirectory:
                                OpenDirectoryHandle();
                                break;
                            case ClickEvent.ReturnDirectory:
                                ReturnDirectoryHandle();
                                break;
                            case ClickEvent.List:
                                ModifyRotateList.Clear();
                                OnActivateListMode();
                                break;
                            default:
                                break;
                        }
                    }

                };
            }
            else
            {
                // Action to process in no save action
                switch (p_iClickEvent)
                {
                    case ClickEvent.ListBoxItemChange:
                        if (listInSearchMode == null)
                        {
                            OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                        }
                        else
                        {
                            OnItemsSelectedToDisplay(listInSearchMode);
                        }
                        break;
                    case ClickEvent.Viewer:
                        OnActivateViewerMode();
                        break;
                    case ClickEvent.List:
                        OnActivateListMode();
                        break;
                    case ClickEvent.ItemDisplay:
                        if (listInSearchMode == null)
                        {
                            OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                        }
                        else
                        {
                            OnItemsSelectedToDisplay(listInSearchMode);
                        }
                        break;
                    case ClickEvent.OpenDirectory:
                        OpenDirectoryHandle();
                        break;
                    case ClickEvent.ReturnDirectory:
                        ReturnDirectoryHandle();
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// Open the current selected directory
        /// </summary>
        public void OpenDirectoryHandle()
        {
            //clear collection files
            ListAllDocFileName.Clear();

            //Raise event
            this.CurrentSelectedDirectory = CurrentSelectedImage.Name;
            OnDirectorySelectedToDisplay(DirectorySelectedEventArgs.Mode.OpenDirectory);
        }

        /// <summary>
        /// Return to the root directory
        /// </summary>
        public void ReturnDirectoryHandle()
        {
            //clear collection files
            ListAllDocFileName.Clear();

            //Raise event
            this.CurrentSelectedDirectory = string.Empty;
            OnDirectorySelectedToDisplay(DirectorySelectedEventArgs.Mode.ReturnDIrectory);
        }

        /// <summary>
        /// Gets the thumbnail list.
        /// </summary>
        /// <param name="p_iSelectedViewerDocIndex">Index of the p_i selected viewer doc.</param>
        /// <param name="p_sDirectory">The P_S directory.</param>
        public void GetThumbnailList(int p_iSelectedViewerDocIndex, string p_sDirectory)
        {
            m_iSelectedViewerDocIndex = p_iSelectedViewerDocIndex;
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

            //** get thumbnail inside a directory
            L_oWCFServiceClient.GetImportThumbNailListFromPathCompleted += L_oWCFServiceClient_GetDocumentThumbNailListFromPathCompleted;
            L_oWCFServiceClient.GetImportThumbNailListFromPathAsync(UserId, this.CurrentSelectedDirectory, ServiceManager.ImportOrderByDescending, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Manage the rank of the document list exclusively for the import module
        /// </summary>
        /// <param name="images">The p_o image rio collection.</param>
        /// <returns></returns>
        public ObservableCollection<ImageRio> ManageDocumentListRank(ObservableCollection<ImageRio> images)
        {
            if (images == null)
                return null;

            ObservableCollection<ImageRio> itemsSource = new ObservableCollection<ImageRio>();
            ListAllDocFileName = new List<string>();

            if ((RankedListFromViewer != null) && (RankedListFromViewer.Count > 0))
            {
                //We compare two collections and add existing items first
                foreach (String rankedListItem in RankedListFromViewer)
                {
                    for (int i = 0; i < images.Count; i++)
                    {
                        if (Utils.RemoveExtension(images[i].Name) == rankedListItem)
                        {
                            //if (ServiceManager.ImportOrderByDescending)
                            //{
                            //    itemsSource.Insert(0, images[i]);
                            //    ListAllDocFileName.Insert(0, Utils.RemoveExtension(images[i].Name));
                            //}
                            //else
                            //{
                                itemsSource.Add(images[i]);
                                ListAllDocFileName.Add(Utils.RemoveExtension(images[i].Name));
                            //}

                            images.RemoveAt(i);
                        }
                    }
                }

                //Then add new items
                //if (ServiceManager.ImportOrderByDescending)
                //{
                //    images.ToList().ForEach(image => itemsSource.Insert(0, image));
                //    images.ToList().ForEach(image => ListAllDocFileName.Insert(0, Utils.RemoveExtension(image.Name)));
                //}
                //else
                //{
                    images.ToList().ForEach(image => itemsSource.Add(image));
                    images.ToList().ForEach(image => ListAllDocFileName.Add(Utils.RemoveExtension(image.Name)));
                //}

                //Reset RankedList
                RankedListFromViewer = null;
            }
            else
            {
                itemsSource = images;
                foreach (ImageRio l_oImg in images)
                {
                    ListAllDocFileName.Add(Utils.RemoveExtension(l_oImg.Name));
                }
            }

            return itemsSource;
        }

        /// <summary>
        /// Saves the modification on thumb nails.
        /// </summary>
        /// <param name="p_oImageRioCollectionToConvert">The image rio collection to convert.</param>
        /// <param name="p_bMergeAfter">The P_B merge after.</param>
        protected void SaveModificationOnThumbNails(IList p_oImageRioCollectionToConvert, bool p_bMergeAfter = false)
        {
            m_oFilesToConvert = p_oImageRioCollectionToConvert;

            try
            {
                if (ModifyRotateList.Count != 0)
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty,
                                                                                 LabelSaveModificationImage,
                                                                                 MessageBoxButtons.YesNo,
                                                                                 MessageBoxIcon.Question);
                    L_oMessage.ShowDialog();
                    L_oMessage.Closed += (s, ev) =>
                    {
                        if (L_oMessage.Result == MessageBoxResult.Yes)
                        {
                            CursorWait(this);
                            Dictionary<bool, ClickEvent> p = new Dictionary<bool, ClickEvent>();
                            ClickEvent ll = new ClickEvent();
                            p.Add(p_bMergeAfter, ll);
                            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                            L_oWCFServiceClient.SaveImportRotatedImagesWithDirectoryCompleted += L_oWCFServiceClient_SaveImportRotatedImagesCompleted;
                            L_oWCFServiceClient.SaveImportRotatedImagesWithDirectoryAsync(ModifyRotateList,
                                                                                         UserId, CurrentSelectedDirectory, ServiceManager.GetLicenseKey(), p);
                            ModifyRotateList.Clear();
                        }
                        else
                        {
                            if (p_bMergeAfter)
                                MergeDocumentInPDF();
                        }
                    };
                    CursorHand(this);
                }
                else
                {
                    if (p_bMergeAfter)
                        MergeDocumentInPDF();
                }
            }
            catch (Exception)
            {
                CursorHand(this);
                throw;
            }
        }

        /// <summary>
        /// Merges the document in PDF.
        /// </summary>
        protected void MergeDocumentInPDF()
        {
            if (m_oFilesToConvert != null && m_oFilesToConvert.Count > 0)
            {
                MessageBoxChildWindow L_oMessagesMergePdf = new MessageBoxChildWindow("", LabelMergePdfQuestion, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                L_oMessagesMergePdf.ShowDialog();

                L_oMessagesMergePdf.Closed += (s, ev) =>
                {
                    if (L_oMessagesMergePdf.Result == MessageBoxResult.Yes)
                    {
                        CursorWait(this);
                        SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_PREPARE_CONVERT);

                        //This is a new converting, so we generate a new Guid
                        m_oGuidSessionToConvert = Guid.NewGuid();

                        //call WCF to prepare converting
                        WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.CreateTemporaryDirectoryCompleted += L_oWCFServiceClient_CreateTemporaryDirectoryCompleted2;
                        L_oWCFServiceClient.CreateTemporaryDirectoryAsync(m_oGuidSessionToConvert.ToString("N"), ServiceManager.GetLicenseKey());
                    }
                    else
                    {
                        CursorNormal(this);
                    }
                };
            }
        }

        /// <summary>
        /// Gets the selected files name to merge in PDF.
        /// </summary>
        /// <param name="p_oSelectedFilesName">Name of the p_o selected files.</param>
        /// <returns></returns>
        protected bool GetSelectedFilesNameToMergeInPDF(List<string> p_oSelectedFilesName)
        {
            Boolean l_bFileFormatOk = true;

            if (p_oSelectedFilesName == null)
                throw new ArgumentException("List must be initialized before!");

            List<string> L_oListExtension = new List<string>();

            //Add the images file extension
            L_oListExtension.AddRange(from Enum item in EnumHelper.GetValues(typeof(Constant.ImageFileFormat))
                                      select Constant.szGetDescription(item));

            //Add the documents file format
            L_oListExtension.AddRange(from Enum item in EnumHelper.GetValues(typeof(Constant.DocumentFileFormat))
                                      select Constant.szGetDescription(item));

            if (m_oFilesToConvert != null && m_oFilesToConvert.Count > 0)
            {
                foreach (ImageRio item in m_oFilesToConvert)
                {
                    //string L_szFileName = Path.GetFileName(item.Name).Substring(0, Path.GetFileName(item.Name).Length - Path.GetExtension(Path.GetFileName(item.Name)).Length);
                    string L_szFileName = Utils.RemoveExtension(item.Name);

                    //The pdf merge is enable only with image file format (Rio.Applications.Web.Services.Constant.ImageFileFormat)
                    if (L_oListExtension.Contains((Path.GetExtension(L_szFileName)).ToLower()))
                    {
                        p_oSelectedFilesName.Add(L_szFileName);
                    }
                    else
                    {
                        l_bFileFormatOk = false;

                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", LabelMergePDFFormatFileError, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.ShowDialog();
                    }
                }
            }

            return l_bFileFormatOk;
        }

        /// <summary>
        /// Gets the list document from selected thumbnails.
        /// </summary>
        /// <returns></returns>
        protected List<Document> GetListDocumentFromSelectedThumbnails()
        {
            List<Document> L_oListDocument = new List<Document>();
            string L_szImageSearchName;

            if ((m_oFilesToConvert != null) && (m_oFilesToConvert.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in m_oFilesToConvert)
                {
                    L_szImageSearchName = imgSearch.ImageName;

                    foreach (Document doc in ListDocument)
                    {
                        if (L_szImageSearchName.Equals(doc.ImageName))
                        {
                            L_oListDocument.Add(doc);
                            break;
                        }
                    }
                }
            }

            return L_oListDocument;
        }

        /// <summary>
        /// Prints the indexed documents (for Search and Flow modes only).
        /// </summary>
        /// <param name="filesToPrint">The files to print.</param>
        protected void PrintIndexedDocuments(IList filesToPrint)
        {
            List<string> L_oFileToPrint = new List<string>();
            if (filesToPrint.Count > 0)
            {
                foreach (ImageRioSearch itemVignette in filesToPrint)
                {
                    //string l_sRelativeDocumentPath = itemVignette.Name.Substring(0, itemVignette.Name.Length - Path.GetExtension(itemVignette.Name).Length);
                    string l_sRelativeDocumentPath = itemVignette.ImageFullPath;
                    L_oFileToPrint.Add(Path.Combine(ParameterStorage, l_sRelativeDocumentPath));
                }
            }

            PrintDocumentsInPDFFormat(L_oFileToPrint);
        }

        /// <summary>
        /// Saves the documents locally.
        /// </summary>
        /// <param name="documentsToSave">The documents to save.</param>
        protected void SaveDocumentsLocally(IList documentsToSave)
        {
            try
            {

                if (documentsToSave.Count == 1)
                {
                    ImageRioSearch l_oSelectedThumbnail = (ImageRioSearch)documentsToSave[0];
                    Document l_oSelectedDocument = ListDocument.Where(f => f.ImageName.Equals(l_oSelectedThumbnail.ImageName)).FirstOrDefault();

                    BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();
                    var query = l_oBecDC.AddActionHistoricQuery((int)Constant.UserActions.TELECHARGEMENT, 0, 0, null, l_oSelectedDocument.ImageName);
                    l_oBecDC.Load(query);

                    //Build URI
                    WebClient webClient = new WebClient();
                    Uri baseUri = new Uri(webClient.BaseAddress);
                    UriBuilder uriBuilder = new UriBuilder(baseUri.Scheme, baseUri.Host, baseUri.Port);

                    string path = uriBuilder.ToString().TrimEnd('/');
                    string filename = "/Rio.Application.FileDownload.aspx?fp=" + Path.Combine(ParameterStorage, l_oSelectedDocument.RelativePath, l_oSelectedDocument.ImageName) + "&name=" + l_oSelectedDocument.OriginalNameFile;

                    VariableDomainContext L_vdcAppVirtualPath = new VariableDomainContext();
                    L_vdcAppVirtualPath.GetAppDomainAppVirtualPath(delegate(InvokeOperation<string> str)
                    {
                        System.Windows.Browser.HtmlPage.Window.Navigate(str.Value == "/"
                                                                            ? new Uri(path + filename, UriKind.Absolute)
                                                                            : new Uri(path + str.Value + filename,
                                                                                      UriKind.Absolute));
                    }
                    , null);
                }
            }
            catch (Exception)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + ex.Message, Logger.Level.Error);
            }
        }

        /// <summary>
        /// Saves the documents locally.
        /// </summary>
        /// <param name="documentsToSave">The documents to save.</param>
        protected void DownloadDocument(Document documentToSave)
        {
            try
            {
                BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();
                var query = l_oBecDC.AddActionHistoricQuery((int)Constant.UserActions.TELECHARGEMENT, 0, 0, null, documentToSave.ImageName);
                l_oBecDC.Load(query);

                //Build URI
                WebClient webClient = new WebClient();
                Uri baseUri = new Uri(webClient.BaseAddress);
                UriBuilder uriBuilder = new UriBuilder(baseUri.Scheme, baseUri.Host, baseUri.Port);

                string path = uriBuilder.ToString().TrimEnd('/');
                string filename = "/Rio.Application.FileDownload.aspx?fp=" + Path.Combine(ParameterStorage, documentToSave.RelativePath, documentToSave.ImageName) + "&name=" + documentToSave.OriginalNameFile;

                VariableDomainContext L_vdcAppVirtualPath = new VariableDomainContext();
                L_vdcAppVirtualPath.GetAppDomainAppVirtualPath(delegate(InvokeOperation<string> str)
                {
                    System.Windows.Browser.HtmlPage.Window.Navigate(str.Value == "/"
                                                                        ? new Uri(path + filename, UriKind.Absolute)
                                                                        : new Uri(path + str.Value + filename,
                                                                                    UriKind.Absolute));
                }
                , null);

            }
            catch (Exception)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + ex.Message, Logger.Level.Error);
            }
        }

        /// <summary>
        /// Deletes the indexed documents.
        /// </summary>
        /// <param name="selectedDocuments">The selected documents.</param>
        /// <param name="callbackMethod">The callback method.</param>
        protected void RemoveOrDeleteSelectedDocuments(List<long> selectedDocuments, Action<LoadOperation<NetBay.Core.BusinessEntities.ReturnObject>> callbackMethod)
        {
            if (selectedDocuments.Count > 0)
            {

                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, LabelDeleteThumbnail, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                L_oMessage.ShowDialog();
                L_oMessage.Closed += (s, ev) =>
                {
                    if (L_oMessage.Result == MessageBoxResult.Yes)
                    {
                        //Launch SplashScreen
                        SplashScreenManager.Wait(this);
                        CursorWait(this);

                        BusinessEntitiesDomainContext l_oBecDC = new BusinessEntitiesDomainContext();

                        try
                        {
                            var query = ConsultationMode == ConsultationModeType.Trash ?
                                l_oBecDC.DeleteDocumentsQuery(selectedDocuments)
                                : l_oBecDC.RemoveDocumentsQuery(selectedDocuments);

                            l_oBecDC.Load(query, callbackMethod, null);
                        }
                        catch (Exception ex)
                        {
                            //Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
                            MessageBoxChildWindow L_oMessageDeleteDocument = new MessageBoxChildWindow("", "Error : " + Environment.NewLine + ex.Message,
                                                                            MessageBoxButtons.Ok, MessageBoxIcon.Error);
                            L_oMessageDeleteDocument.ShowDialog();
                        }
                    }
                };
            }
        }

        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <param name="documents">The documents.</param>
        protected void SendMail(List<NetBay.Core.BusinessEntities.Document> documents)
        {
            if (documents != null && documents.Count > 0)
            {
                EmailWindow l_oEmailWindow = new EmailWindow(m_oCurrentOrganization, documents, ParameterStorage);
                l_oEmailWindow.ShowDialog();
            }
        }

        /// <summary>
        /// Ventilates the documents.
        /// </summary>
        /// <param name="filestoVentilate">The filesto ventilate.</param>
        protected void VentilateDocuments(IList filestoVentilate)
        {
            List<long> l_oDocumentListToVentil = new List<long>();

            if (filestoVentilate.Count != 0)
            {
                foreach (ImageRioSearch itemVignette in filestoVentilate)
                {
                    Document l_oSelectedDocument = ListDocument.Where(f => f.ImageName == itemVignette.ImageName).FirstOrDefault();
                    if (l_oSelectedDocument != null) l_oDocumentListToVentil.Add(l_oSelectedDocument.Identifier);
                }
            }

            VentilateWindow l_oVentilWindow = new VentilateWindow(l_oDocumentListToVentil, 0, UserId, string.Empty);
            l_oVentilWindow.ShowDialog();
        }

        /// <summary>
        /// Shows the folder link window.
        /// </summary>
        protected void ShowFolderLinkWindow()
        {
            if (m_oCurrentOrganization != null && m_oFolder != null)
            {
                FolderLinkChildWindow l_oEmailWindow = new FolderLinkChildWindow(m_oCurrentOrganization, m_oFolder);
                l_oEmailWindow.ShowDialog();
            }
        }

        #endregion

        #region Cursor

        /// <summary>
        /// Restore the normal cursor
        /// </summary>
        protected override void CursorNormal(FrameworkElement p_oFWElement)
        {
            base.CursorNormal(p_oFWElement);
            OnDisplayCompleted();
        }
        /// <summary>
        /// Initialize the Hand cursor
        /// </summary>
        protected override void CursorHand(FrameworkElement p_oFWElement)
        {
            base.CursorHand(p_oFWElement);
            OnDisplayCompleted();
        }

        #endregion

        #region Drag and drop

        /// <summary>
        /// Called when [drag query].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.DragDrop.DragDropQueryEventArgs" /> instance containing the event data.</param>
        protected void OnDragQuery(object sender, DragDropQueryEventArgs e)
        {
            if (e.Options.Status
                == DragStatus.DragQuery)
            {
                e.QueryResult = true;
                e.Handled = true;

                var sourceControl = sender as ListBox;

                if (sourceControl != null)
                {
                    //Set up a drag cue:
                    TreeViewDragCue cue = new TreeViewDragCue();
                    cue.ItemTemplate = Resources["DargAndDropTemplate"] as DataTemplate;

                    List<object> L_oObject = new List<object>();
                    L_oObject.Add(sourceControl.DataContext);

                    cue.ItemsSource = L_oObject;

                    e.Options.DragCue = cue;

                    if (CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.ImportDirectory || CurrentDisplayMode == AppDisplayMode.AddDocument)
                    {
                        e.Options.Payload = new DragDropOperation()
                                                {
                                                    Payload =
                                                        (sourceControl.SelectedItems as ObservableCollection<object>).
                                                        Cast<ImageRio>().ToList()
                                                };
                    }
                    else
                    {
                        e.Options.Payload = new DragDropOperation()
                        {
                            Payload =
                                (sourceControl.SelectedItems as ObservableCollection<object>).
                                Cast<ImageRioSearch>().ToList()
                        };
                    }
                }
            }

            if (e.Options.Status
                == DragStatus.DropSourceQuery)
            {
                e.QueryResult = true;
                e.Handled = true;
            }
        }

        /// <summary>
        /// Called when [drop info].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.DragDrop.DragDropEventArgs" /> instance containing the event data.</param>
        protected virtual void OnDropInfo(object sender, DragDropEventArgs e)
        {
            // Get the drag cue that the TreeView or we have created
            TreeViewDragCue cue = e.Options.DragCue as TreeViewDragCue;

            if (e.Options.Status == DragStatus.DropPossible)
            {
                if (cue != null)
                    cue.IsDropPossible = true;

                var listBox = e.Options.Destination.FindItemsConrolParent() as ListBox;
                VisualStateManager.GoToState(listBox, "DropPossible", false);
                ListBoxItem destination = e.Options.Destination as ListBoxItem;

                //Get the DropCueElemet:
                var LBFrameworkElement = VisualTreeHelper.GetChild(listBox, 0) as FrameworkElement;
                if (LBFrameworkElement != null)
                {
                    Grid dropCueElement = LBFrameworkElement.FindName("DropCueElement") as Grid;

                    DragDropOperation operation = e.Options.Payload as DragDropOperation;

                    //Get the parent of the destination:
                    WrapPanel visParent = VisualTreeHelper.GetParent(destination) as WrapPanel;

                    //Get the spacial relation between the destination and its parent:
                    Point destinationStackTopLeft = destination.TransformToVisual(visParent).Transform(new Point());

                    if (operation != null)
                    {
                        //X Translation to place the drag cursor (DropCueElement) at the right column in the WrapPanel
                        var xTranslateValue = operation.DropPosition == DropPosition.Before
                                                  ? destinationStackTopLeft.X
                                                  : destinationStackTopLeft.X + destination.ActualWidth;

                        //Y Translation to place the drag cursor (DropCueElement) at the right line in the WrapPanel
                        var yTranslateValue = destinationStackTopLeft.Y;

                        if (dropCueElement != null)
                        {
                            dropCueElement.RenderTransform = new TranslateTransform() { X = xTranslateValue, Y = yTranslateValue };
                        }
                    }
                }
            }

            //Hide the DropCue:
            if (e.Options.Status == DragStatus.DropImpossible || e.Options.Status == DragStatus.DropCancel || e.Options.Status == DragStatus.DropComplete)
            {
                if (cue != null)
                    cue.IsDropPossible = false;

                var listBox = e.Options.Destination.FindItemsConrolParent() as ListBox;
                VisualStateManager.GoToState(listBox, "DropImpossible", false);
            }

            //Place the item:
            if (e.Options.Status == DragStatus.DropComplete)
            {
                var listBox = e.Options.Destination.FindItemsConrolParent() as ListBox;
                if (listBox != null)
                {
                    var itemsSource = listBox.ItemsSource as IList;
                    if (itemsSource != null)
                    {

                        var operation = e.Options.Payload as DragDropOperation;
                        if (operation != null)
                        {
                            var selectedItems = GetSelectedImage<ImageRio>();

                            foreach (var imageRio in selectedItems)
                            {
                                itemsSource.Remove(imageRio);
                                var destinationIndex = itemsSource.IndexOf(e.Options.Destination.DataContext);

                                var insertIndex = operation.DropPosition == DropPosition.Before
                                                      ? destinationIndex
                                                      : destinationIndex + 1;


                                itemsSource.Insert(insertIndex, imageRio);

                                for (var i = 0; i < itemsSource.Count - 1; i++)
                                {
                                    if (ListAllDocFileName == null)
                                        ListAllDocFileName = new List<string>();

                                    if (CurrentDisplayMode == AppDisplayMode.Search || CurrentDisplayMode == AppDisplayMode.Flow)
                                    {
                                        ListAllDocFileName.Add(Path.GetFileNameWithoutExtension(((ImageRioSearch)itemsSource[i]).Name));
                                    }
                                    else
                                    {
                                        ListAllDocFileName[i] = Utils.RemoveExtension(((ImageRio)itemsSource[i]).Name);
                                    }
                                }

                                SetActuallyRankingList();

                                listBox.Dispatcher.BeginInvoke(() =>
                                {
                                    listBox.SelectedIndex = insertIndex;
                                });
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Called when [drop query].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.DragDrop.DragDropQueryEventArgs" /> instance containing the event data.</param>
        protected void OnDropQuery(object sender, DragDropQueryEventArgs e)
        {
            if (e.Options.Status == DragStatus.DropDestinationQuery)
            {
                var destination = e.Options.Destination;
                var listBox = destination.FindItemsConrolParent() as ListBox;

                //Cannot place na item relative to itself:
                if (e.Options.Source == e.Options.Destination)
                {
                    return;
                }

                VisualStateManager.GoToState(listBox, "DropPossible", false);

                //Get the spacial relation between the destination item and the vis. root:
                var destinationTopLeft = destination.TransformToVisual(null).Transform(new Point());

                //Should the new Item be moved before or after the destination item?:
                bool placeBefore = (e.Options.CurrentDragPoint.X - destinationTopLeft.X) < destination.ActualWidth / 2;

                var operation = e.Options.Payload as DragDropOperation;
                if (operation != null)
                    operation.DropPosition = placeBefore ? DropPosition.Before : DropPosition.After;

                e.QueryResult = true;
                e.Handled = true;
            }
        }

        #endregion

        #region Rotates functions

        /// <summary>
        /// Apply the rotate to image of document (call WCFServices)
        /// </summary>
        /// <param name="p_oDelegateDisplaySourceDocument"></param>
        /// <param name="p_szParameterStorageImage"></param>
        /// <param name="p_szFileNameOrRelativePath"></param>
        /// <param name="p_aRawImage">Raw Image</param>
        /// <param name="p_bRotateRight">Indicate the type of rotation</param>
        /// <param name="p_iIndexDocumentSelected">Index of selected document</param>
        /// <param name="p_iIndexPage">Index of page to rotate</param>
        /// <param name="p_bForceAllPages">Force the rotation to all pages</param>
        /// <param name="p_iNbPages">Number of pages from document</param>
        protected void RotateDocumentWCFServices(RefreshSourceDocumentHandler p_oDelegateDisplaySourceDocument, string p_szParameterStorageImage, string p_szFileNameOrRelativePath, Byte[] p_aRawImage, bool p_bRotateRight, int p_iIndexDocumentSelected, int p_iIndexPage, bool p_bForceAllPages, int p_iNbPages = 1)
        {
            if (VerifyFilter(p_szFileNameOrRelativePath))
            {
                // Determine the identification of the document
                string l_szFileNameOrFullPath = p_szFileNameOrRelativePath;
                if (CurrentDisplayMode == AppDisplayMode.Search)
                {
                    l_szFileNameOrFullPath = Path.Combine(p_szParameterStorageImage, p_szFileNameOrRelativePath);
                }
                else
                {
                    // Rotate the image of document in the dictionary
                    // To See : Save Modif on Search

                    RotateImageInDictionary(l_szFileNameOrFullPath, p_bRotateRight, p_iIndexPage, p_bForceAllPages, p_iNbPages);
                }

                // Determine the rotation to send to WCFServices
                RotateFlipType l_iRotateFlipType = RotateFlipType.Rotate270FlipNone;
                if (p_bRotateRight)
                    l_iRotateFlipType = RotateFlipType.Rotate90FlipNone;

                // Ge number of pages
                WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                L_oWCFServiceClient.RotateImageCompleted += L_oWCFServiceClient_RotateImageCompleted;
                L_oWCFServiceClient.RotateImageAsync(
                    p_aRawImage, l_iRotateFlipType, Path.GetExtension((l_szFileNameOrFullPath)), ServiceManager.GetLicenseKey(), Tuple.Create(
                        p_iIndexDocumentSelected,
                        p_iNbPages,
                        p_oDelegateDisplaySourceDocument
                        )
                    );
                // Show the wait cursor
                CursorWait(this);
            }
            else
            {
                CursorHand(this);
            }
        }
        /// <summary>
        /// Save the RotateFlipType for current image of page in the dictionary
        /// </summary>
        /// <param name="p_szFileName">Filename of page</param>
        /// <param name="p_bRotateRight">Indicate the type of rotation</param>
        /// <param name="p_iIndexPage">Index of page to rotate</param>
        /// <param name="p_bForceAllPages">Force the rotation to all pages</param>
        /// <param name="p_iNbPages">Number of pages from document</param>
        private void RotateImageInDictionary(string p_szFileName, bool p_bRotateRight, int p_iIndexPage, bool p_bForceAllPages, int p_iNbPages)
        {
            if (ModifyRotateList.Keys.Contains(p_szFileName) == true)
            {
                RotateFlipType l_iRotateFlipType = ModifyRotateList[p_szFileName][p_iIndexPage - 1];

                switch (l_iRotateFlipType)
                {
                    case RotateFlipType.RotateNoneFlipNone:
                        l_iRotateFlipType = p_bRotateRight ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
                        break;
                    case RotateFlipType.Rotate90FlipNone:
                        l_iRotateFlipType = p_bRotateRight
                                                ? RotateFlipType.Rotate180FlipNone : RotateFlipType.RotateNoneFlipNone;
                        break;
                    case RotateFlipType.Rotate180FlipNone:
                        l_iRotateFlipType = p_bRotateRight
                                                ? RotateFlipType.Rotate270FlipNone : RotateFlipType.Rotate90FlipNone;
                        break;
                    case RotateFlipType.Rotate270FlipNone:
                        l_iRotateFlipType = p_bRotateRight
                                                ? RotateFlipType.RotateNoneFlipNone : RotateFlipType.Rotate180FlipNone;
                        break;
                }

                // Affect the new RotateFlipType value (p_iIndexPage)
                if (p_bForceAllPages)
                {
                    if (l_iRotateFlipType == RotateFlipType.RotateNoneFlipNone)
                    {
                        ModifyRotateList.Remove(p_szFileName);
                    }
                    else
                    {
                        for (int iLoop = 0; iLoop < p_iNbPages; iLoop++)
                        {
                            ModifyRotateList[p_szFileName][iLoop] = l_iRotateFlipType;
                        }
                    }
                }
                else
                {

                    if (l_iRotateFlipType == RotateFlipType.RotateNoneFlipNone)
                    {
                        ModifyRotateList.Remove(p_szFileName);
                    }
                    else
                    {
                        ModifyRotateList[p_szFileName][p_iIndexPage - 1] = l_iRotateFlipType;
                    }
                }

            }
            else
            {
                Dictionary<int, RotateFlipType> l_temp = new Dictionary<int, RotateFlipType>();
                if (p_iNbPages > 0)
                {
                    for (int i = 0; i < p_iNbPages; i++)
                    {
                        if (
                            (i == p_iIndexPage - 1)
                            || p_bForceAllPages
                            )
                        {
                            l_temp.Add(i, p_bRotateRight == true ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
                        }
                        else
                        {
                            l_temp.Add(i, RotateFlipType.RotateNoneFlipNone);
                        }
                    }
                }
                else
                {
                    l_temp.Add(0, p_bRotateRight == true ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
                }

                ModifyRotateList.Add(p_szFileName, l_temp);
            }

            //Manage toolbar to update the save modification button
            ManageToolbarState();

        }
        /// <summary>
        /// Verify if the extension of file is supported
        /// </summary>
        /// <param name="P_FileName">FileName of documnet</param>
        /// <returns></returns>
        protected bool VerifyFilter(string P_FileName)
        {
            string[] l_oFilePath = P_FileName.Split('#');
            foreach (Enum FileFormat in EnumHelper.GetValues(typeof(Constant.ImageFileFormat)))
            {
                if (Path.GetExtension(l_oFilePath[0]).ToLower().Equals(Constant.szGetDescription(FileFormat)) ||
                    Path.GetExtension(l_oFilePath[0]).ToLower().Equals(".pdf"))
                {
                    return true;
                }
            }

            return false;
        }
        #endregion

        #region WCF Services Completed Handles

        /// <summary>
        /// Handles the RotateImageCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_RotateImageCompleted(object sender, RotateImageCompletedEventArgs e)
        {

            // Restore the normal cursor
            CursorNormal(this);

            if (e.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + e.Error.Message, Logger.Level.Error);
                MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Error On RotateImage() -> " + e.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessageGetDocument.ShowDialog();
            }
            else
            {
                ReturnByte l_oReturnByte = e.Result;
                if (l_oReturnByte.IsValid == false)
                {
                    //Logger.Write("NOT VALID : " + Environment.NewLine + l_oReturnByte.ErrorMessage, Logger.Level.Error);
                    MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", "Response not valid On RotateImage() -> " + l_oReturnByte.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessageGetDocument.ShowDialog();
                }
                else
                {
                    Tuple<int, int, RefreshSourceDocumentHandler> l_oRet =
                        (Tuple<int, int, RefreshSourceDocumentHandler>)e.UserState;
                    if (l_oRet.Item3 != null)
                    {
                        ((RefreshSourceDocumentHandler)l_oRet.Item3)(l_oReturnByte.Value, l_oRet.Item1, l_oRet.Item2);
                    }
                }
            }

        }

        /// <summary>
        /// Handles the DeleteImportDocumentCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.DeleteImportDocumentCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_DeleteImportImagesCompleted(object sender, DeleteImportImagesCompletedEventArgs e)
        {

            if (!e.Result.IsValid)
            {
                ////Add name of file in error list
                //m_oFilenamesErrorDuringDeleting.Add(m_oFilenamesToDelete.Pop().Name);
            }
            else
            {
                ObservableCollection<ImageRio> m_oFilesToDelete = new ObservableCollection<ImageRio>(e.UserState as ObservableCollection<ImageRio>);

                /*
                 * Delete current document in thumbnail list and in ModifyRotateList
                 */
                for (int i = 0; i < m_oFilesToDelete.Count; i++)
                {
                    if (ModifyRotateList.ContainsKey(Utils.RemoveExtension(m_oFilesToDelete[i].Name)))
                    {
                        ModifyRotateList.Remove(Utils.RemoveExtension(m_oFilesToDelete[i].Name));
                    }
                    OnImportedDocumentDeleted(m_oFilesToDelete[i]);
                    ListAllDocFileName.Remove(Utils.RemoveExtension(m_oFilesToDelete[i].Name));
                }
                m_oFilesToDelete.Clear();

            }

            SplashScreenManager.Stop(this);
            CursorNormal(this);
        }

        /// <summary>
        /// Handles the SaveImportRotatedImagesCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_SaveImportRotatedImagesCompleted(object sender, SaveImportRotatedImagesWithDirectoryCompletedEventArgs e)
        {
            bool l_bMergeAfter = false;

            if (e != null && e.Error != null)
            {
                LoggerHelper.Send(this.GetType().Name, e.Error.Message);
                CursorHand(this);
            }
            else if (e != null && e.UserState != null)
            {
                Dictionary<bool, ClickEvent> p = (Dictionary<bool, ClickEvent>)e.UserState;
                foreach (bool l_oneBool in p.Keys)
                {
                    l_bMergeAfter = l_oneBool;
                }

                ClickEvent l_oclickEvent = p[l_bMergeAfter];

                // Action to process immediatly and whatever the user choice
                switch (l_oclickEvent)
                {
                    case ClickEvent.ListBoxItemChange:
                        OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                        ModifyRotateList.Clear();
                        break;
                    case ClickEvent.ItemDisplay:
                        OnItemsSelectedToDisplay(GetListDocumentFromSelectedThumbnails());
                        ModifyRotateList.Clear();
                        break;
                    case ClickEvent.SaveModification:
                        ModifyRotateList.Clear();
                        break;
                    case ClickEvent.Viewer:
                        ModifyRotateList.Clear();
                        OnActivateViewerMode();
                        break;
                    case ClickEvent.List:
                        ModifyRotateList.Clear();
                        OnActivateListMode();
                        break;
                    case ClickEvent.OpenDirectory:
                        ModifyRotateList.Clear();
                        OpenDirectoryHandle();
                        break;
                    case ClickEvent.ReturnDirectory:
                        ModifyRotateList.Clear();
                        ReturnDirectoryHandle();
                        break;
                }

                ReturnObject l_oReturn = e.Result;
                if (l_oReturn.IsValid)
                {
                    if (l_bMergeAfter)
                    {
                        MergeDocumentInPDF();
                    }
                    else
                    {
                        CursorHand(this);
                    }
                }
                else
                {
                    LoggerHelper.Send(this.GetType().Name, "Return object is not valid");
                    CursorHand(this);
                }

                //Update toolbar 
                ManageToolbarState();

            }
        }

        /// <summary>
        /// Handles the GetDocumentThumbNailListCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.GetImportThumbNailListCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_GetDocumentThumbNailListFromPathCompleted(object sender, GetImportThumbNailListFromPathCompletedEventArgs e)
        {
            ObservableCollection<ImageRio> imageRioCollectionReturn = null;
            if (e.Error != null)
            {
                LoggerHelper.Send(this.GetType().Name + "L_oWCFServiceClient_GetDocumentThumbNailListCompleted", e.Error.Message);
            }
            else
            {
                if (e.Result != null)
                {
                    imageRioCollectionReturn = new ObservableCollection<ImageRio>(e.Result);
                }
            }
            //raise OnImportedDocumentRefreshed event
            OnImportedDocumentRefreshed(imageRioCollectionReturn);
        }

        /// <summary>
        /// Handles the CreateTemporaryDirectoryCompleted2 event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_CreateTemporaryDirectoryCompleted2(object sender, CreateTemporaryDirectoryCompletedEventArgs e)
        {
            //Clean and prepare objects to converting
            m_oFilenamesToConvert.Clear();
            m_iCurrentIndextoFilenamesToConvert = 0;

            if (e.Result.IsValid)
            {
                //Retry selected documents according to allowed extensions
                if (GetSelectedFilesNameToMergeInPDF(m_oFilenamesToConvert))
                {
                    SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_CONVERTING);
                    SplashScreenManager.SplashScreen.MessageDetail = m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert];

                    //Initialize pogress bar
                    SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = Visibility.Visible;
                    SplashScreenManager.SplashScreen.ProgressBarProcess.Minimum = 0;
                    SplashScreenManager.SplashScreen.ProgressBarProcess.Maximum = m_oFilenamesToConvert.Count;
                    SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;

                    //Launch converting
                    WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                    L_oWCFServiceClient.ConvertDocumentAppendCompleted += L_oWCFServiceClient_ConvertDocumentAppendCompleted2;
                    L_oWCFServiceClient.ConvertDocumentAppendAsync(m_oGuidSessionToConvert.ToString("N"), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert], UserId, ServiceManager.GetLicenseKey(), true);
                }
            }
            else
            {
                OnImportedDocumentMergedFailed();
                CursorNormal(this);
            }
        }

        /// <summary>
        /// Handles the ConvertDocumentAppendCompleted2 event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_ConvertDocumentAppendCompleted2(object sender, ConvertDocumentAppendCompletedEventArgs e)
        {
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

            if (e.Result.IsValid)
            {
                ConvertNextDocument2(L_oWCFServiceClient);
            }
            else
            {
                //Treat error
                MessageBoxChildWindow errorMessageBox = new MessageBoxChildWindow(
                    String.Empty,
                    String.Format(Resx.GetLabel(ResxCommon.FORMAT_ERROR_WHILE_PROCESSING), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert]),
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                errorMessageBox.ShowDialog();
                errorMessageBox.Closed += (s, ev) =>
                {
                    if (errorMessageBox.DialogResult == true)
                    {
                        //Set null on error document from files to convert to avoid deleting at finish
                        m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert] = null;

                        //Skip & continue transfert
                        ConvertNextDocument2(L_oWCFServiceClient);
                    }
                    else
                    {
                        AbortMergePdf(L_oWCFServiceClient);
                    }
                };
            }
        }



        /// <summary>
        /// Handles the CarveImportFilesCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_CarveImportFilesCompleted(object sender, CarveImportFilesCompletedEventArgs e)
        {
            if (e.Result.IsValid)
            {
                GetThumbnailList(-1, this.CurrentSelectedDirectory);
            }
        }

        /// <summary>
        /// Handles the CreateTemporaryDirectoryCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.CreateTemporaryDirectoryCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_CreateTemporaryDirectoryCompleted(object sender, CreateTemporaryDirectoryCompletedEventArgs e)
        {
            if (e.Result.IsValid)
            {
                SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_CONVERTING);
                SplashScreenManager.SplashScreen.MessageDetail = Path.GetFileName(m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert]);

                //Initialize pogress bar
                SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = System.Windows.Visibility.Visible;
                SplashScreenManager.SplashScreen.ProgressBarProcess.Minimum = 0;
                SplashScreenManager.SplashScreen.ProgressBarProcess.Maximum = m_oFilenamesToConvert.Count;
                SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;

                //Launch converting
                WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                L_oWCFServiceClient.ConvertDocumentAppendCompleted += L_oWCFServiceClient_ConvertDocumentAppendCompleted;
                L_oWCFServiceClient.ConvertDocumentAppendAsync(m_oGuidSessionToConvert.ToString("N"), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert], UserId, ServiceManager.GetLicenseKey(), false);
            }
            else
            {
                CursorNormal(this);
            }
        }

        /// <summary>
        /// Handles the ConvertDocumentAppendCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.ConvertDocumentAppendCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_ConvertDocumentAppendCompleted(object sender, ConvertDocumentAppendCompletedEventArgs e)
        {
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

            if (e.Result.IsValid)
            {
                ConvertNextDocument(L_oWCFServiceClient);
            }
            else
            {
                //Treat error
                MessageBoxChildWindow errorMessageBox = new MessageBoxChildWindow(
                    String.Empty,
                    String.Format(Resx.GetLabel(ResxCommon.FORMAT_ERROR_WHILE_PROCESSING), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert]),
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                errorMessageBox.ShowDialog();
                errorMessageBox.Closed += (s, ev) =>
                    {
                        if (errorMessageBox.DialogResult == true)
                        {
                            //Delete error document from files to convert to avoid deleting at finish
                            m_oFilenamesToConvert.RemoveAt(m_iCurrentIndextoFilenamesToConvert);

                            //Skip & continue transfert
                            ConvertNextDocument(L_oWCFServiceClient);
                        }
                        else
                        {
                            AbortMergePdf(L_oWCFServiceClient);
                        }
                    };
            }
        }

        /// <summary>
        /// Handles the ConvertDocumentFinishCompleted2 event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.ConvertDocumentFinishCompletedEventArgs" /> instance containing the event data.</param>
        private void L_oWCFServiceClient_ConvertDocumentFinishCompleted2(object sender, ConvertDocumentFinishCompletedEventArgs e)
        {
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

            SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = Visibility.Collapsed;
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;

            //Delete temporary directory
            L_oWCFServiceClient.DeleteTemporaryDirectoryCompleted += (s, ev) =>
            {
                //Delete all imported documen who have been converted
                L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

                L_oWCFServiceClient.DeleteImportDocumentCompleted += (o, ew) =>
                {
                    SetActuallyRankingList();

                    m_oFilenamesToConvert.Clear();

                    OnRefreshThumbnails();

                    CursorNormal(this);
                };

                L_oWCFServiceClient.DeleteImportDocumentAsync(new ObservableCollection<string>(m_oFilenamesToConvert), UserId, ServiceManager.GetLicenseKey());
            };

            L_oWCFServiceClient.DeleteTemporaryDirectoryAsync(m_oGuidSessionToConvert.ToString("N"), ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Handles the ConvertDocumentFinishCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.ConvertDocumentFinishCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_ConvertDocumentFinishCompleted(object sender, ConvertDocumentFinishCompletedEventArgs e)
        {
            SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = Visibility.Collapsed;
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;

            if (!String.IsNullOrEmpty(e.Result.Value))
            {
                //Prepare Url to downloading
                string path = HtmlPage.Document.DocumentUri.AbsoluteUri;
                if (!String.IsNullOrWhiteSpace(HtmlPage.Document.DocumentUri.Fragment))
                    path = path.Replace(HtmlPage.Document.DocumentUri.Fragment, String.Empty);
                path = path.Replace(HtmlPage.Document.DocumentUri.LocalPath, String.Empty);

                const string filename = "/Rio.Application.OpenPDF.aspx";
                string l_szParameters = String.Format("?fld={0}", HttpUtility.UrlEncode(e.Result.Value));
                VariableDomainContext L_vdcAppVirtualPath = new VariableDomainContext();
                L_vdcAppVirtualPath.GetAppDomainAppVirtualPath(
                    str => System.Windows.Browser.HtmlPage.Window.Navigate(
                        str.Value == "/" ? new Uri(path + filename + l_szParameters, UriKind.Absolute) : new Uri(path + str.Value + filename + l_szParameters, UriKind.Absolute),
                        "_blank",
                        "toolbar=no,location=no,status=no,menubar=no,resizable=yes,titlebar=no"),
                    null);
            }

            CursorNormal(this);
        }
        #endregion

        #region Private

        /// <summary>
        /// Fires the on initialisation completed.
        /// </summary>
        protected void FireOnInitialisationCompleted()
        {
            if (!_IsViewerInitialized)
            {
                OnInitialisationCompleted();
                _IsViewerInitialized = true;
            }
        }

        /// <summary>
        /// Aborts the merge PDF.
        /// </summary>
        /// <param name="L_oWCFServiceClient">The l_o WCF service client.</param>
        private void AbortMergePdf(WCFServiceClient L_oWCFServiceClient)
        {
            //Delete Temporary directory
            L_oWCFServiceClient.DeleteTemporaryDirectoryAsync(m_oGuidSessionToConvert.ToString("N"), ServiceManager.GetLicenseKey());

            OnImportedDocumentMergedFailed();

            CursorNormal(this);

            SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = Visibility.Collapsed;
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;
        }

        /// <summary>
        /// Converts the next document.
        /// </summary>
        /// <param name="L_oWCFServiceClient">The l_o WCF service client.</param>
        private void ConvertNextDocument(WCFServiceClient L_oWCFServiceClient)
        {
            //Increment index
            m_iCurrentIndextoFilenamesToConvert++;

            //Notify user of progression
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value++;

            if (m_iCurrentIndextoFilenamesToConvert < m_oFilenamesToConvert.Count)
            {
                //Notify user
                SplashScreenManager.SplashScreen.MessageDetail = Path.GetFileName(m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert]);

                //Continue converting with next document
                L_oWCFServiceClient.ConvertDocumentAppendCompleted += L_oWCFServiceClient_ConvertDocumentAppendCompleted;
                L_oWCFServiceClient.ConvertDocumentAppendAsync(m_oGuidSessionToConvert.ToString("N"), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert], UserId, ServiceManager.GetLicenseKey(), false);
            }
            else
            {
                //IF there is items who need finalizing
                if (m_oFilenamesToConvert.Count > 0)
                {
                    //Converting is finished
                    SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_FINALIZING);
                    SplashScreenManager.SplashScreen.MessageDetail = String.Empty;

                    //Finalize converting
                    L_oWCFServiceClient.ConvertDocumentFinishCompleted += L_oWCFServiceClient_ConvertDocumentFinishCompleted;
                    L_oWCFServiceClient.ConvertDocumentFinishAsync(m_oGuidSessionToConvert.ToString("N"), UserId, ServiceManager.GetLicenseKey(), true);
                }
                else
                {
                    AbortMergePdf(L_oWCFServiceClient);
                }
            }
        }

        /// <summary>
        /// Converts the next document.
        /// </summary>
        /// <param name="L_oWCFServiceClient">The l_o WCF service client.</param>
        private void ConvertNextDocument2(WCFServiceClient L_oWCFServiceClient)
        {
            //Increment index
            m_iCurrentIndextoFilenamesToConvert++;

            //Notify user of progression
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value++;

            if (m_iCurrentIndextoFilenamesToConvert < m_oFilenamesToConvert.Count)
            {
                //Notify user
                SplashScreenManager.SplashScreen.MessageDetail = Path.GetFileName(m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert]);

                //Continue converting with next document
                L_oWCFServiceClient.ConvertDocumentAppendCompleted += L_oWCFServiceClient_ConvertDocumentAppendCompleted2;
                L_oWCFServiceClient.ConvertDocumentAppendAsync(m_oGuidSessionToConvert.ToString("N"), m_oFilenamesToConvert[m_iCurrentIndextoFilenamesToConvert], UserId, ServiceManager.GetLicenseKey(), true);
            }
            else
            {
                //IF there is items who need finalizing
                if (m_oFilenamesToConvert.Count > 0)
                {
                    //Converting is finished
                    SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxCommon.MSG_FINALIZING);
                    SplashScreenManager.SplashScreen.MessageDetail = String.Empty;

                    //Finalize converting
                    L_oWCFServiceClient.ConvertDocumentFinishCompleted += L_oWCFServiceClient_ConvertDocumentFinishCompleted2;
                    L_oWCFServiceClient.ConvertDocumentFinishAsync(m_oGuidSessionToConvert.ToString("N"), UserId, ServiceManager.GetLicenseKey(), false);
                }
                else
                {
                    AbortMergePdf(L_oWCFServiceClient);
                }
            }
        }

        #endregion

        #region Copy-Cut-Paste

        /// <summary>
        /// Cut action
        /// </summary>
        private void CutDocuments(List<long> identifiers)
        {
            //List<long> identifiers = GetListIdentifierToCopy();
            GlobalWebContext.CopyPasteManager.ClearDocuments();
            GlobalWebContext.CopyPasteManager.IsOriginalVersion = this.displayedVersion != null ? displayedVersion.IsOriginalVersion : false;
            GlobalWebContext.CopyPasteManager.VersionIdentifier = this.displayedVersion != null ? displayedVersion.VersionId : 0;
            GlobalWebContext.CopyPasteManager.ActionType = PasteCopyActionType.Cut;
            GlobalWebContext.CopyPasteManager.SourceFolder = m_oFolder;
            GlobalWebContext.CopyPasteManager.Documents = identifiers;
        }

        /// <summary>
        /// Copy action
        /// </summary>
        private void CopyDocuments(List<long> identifiers)
        {
            //List<long> identifiers = GetListIdentifierToCopy();
            GlobalWebContext.CopyPasteManager.ClearDocuments();
            GlobalWebContext.CopyPasteManager.IsOriginalVersion = this.displayedVersion != null ? displayedVersion.IsOriginalVersion : false;
            GlobalWebContext.CopyPasteManager.VersionIdentifier = this.displayedVersion != null ? displayedVersion.VersionId : 0;
            GlobalWebContext.CopyPasteManager.ActionType = PasteCopyActionType.Copy;
            GlobalWebContext.CopyPasteManager.SourceFolder = m_oFolder;
            GlobalWebContext.CopyPasteManager.Documents = identifiers;
        }

        /// <summary>
        /// Remove a copied document
        /// </summary>
        protected void RemoveCopiedDocument(long identifier)
        {
            GlobalWebContext.CopyPasteManager.RemoveDocument(identifier);
        }

        /// <summary>
        /// Get the list of selected identifier (in search mode only). Must be implemented in child class!
        /// </summary>
        /// <returns>List of <see cref="long"/></returns>
        protected virtual List<long> GetListIdentifierToCopy()
        {
            return new List<long>();
        }

        /// <summary>
        /// Cut action
        /// </summary>
        protected void OnCutClick()
        {
            List<long> identifiers = GetListIdentifierToCopy();
            if (identifiers.Count > 0)
            {
                PasteCopyEventArgs args = new PasteCopyEventArgs(PasteCopyActionType.Cut, null, identifiers);

                //Raise event
                if (BeforeCopyPasteDocuments != null)
                    BeforeCopyPasteDocuments(this, args);

                //If not canceled 
                if (!args.Cancel)
                {
                    CutDocuments(args.Documents);
                    OnToolbarStateHasChanged();

                    //Raise event
                    if (CopyPasteDocuments != null)
                        CopyPasteDocuments(this, args);
                }
            }
        }

        /// <summary>
        /// Copy action
        /// </summary>
        protected void OnCopyClick()
        {
            List<long> identifiers = GetListIdentifierToCopy();
            if (identifiers.Count > 0)
            {
                PasteCopyEventArgs args = new PasteCopyEventArgs(PasteCopyActionType.Copy, null, identifiers);

                //Raise event
                if (BeforeCopyPasteDocuments != null)
                    BeforeCopyPasteDocuments(this, args);

                //If not canceled 
                if (!args.Cancel)
                {
                    CopyDocuments(args.Documents);
                    OnToolbarStateHasChanged();

                    //Raise event
                    if (CopyPasteDocuments != null)
                        CopyPasteDocuments(this, args);
                }
            }
        }

        /// <summary>
        /// Paste action
        /// </summary>
        protected void OnPasteClick()
        {
            PasteCopyEventArgs args = new PasteCopyEventArgs(PasteCopyActionType.Paste);

            //Raise event
            if (BeforeCopyPasteDocuments != null)
                BeforeCopyPasteDocuments(this, args);

            //If not canceled 
            if (!args.Cancel)
            {
                //Just raise event, the action is done in FolderPage...
                if (CopyPasteDocuments != null)
                    CopyPasteDocuments(this, args);
            }
        }

        /// <summary>
        /// Updates the copy paste selection.
        /// </summary>
        public virtual void UpdateCopyPasteSelection()
        {
        }

        #endregion

        #region Versioning

        protected void OnCheckOutClick()
        {
            if (ListDocument[SelectedDocumentIndex].CurrentModelVersion != null)
            {

                String l_sDocumentPath = Path.Combine(ListDocument[SelectedDocumentIndex].RelativePath, ListDocument[SelectedDocumentIndex].ImageName);
                this._saveFileDialog.DefaultFileName = Path.GetFileName(l_sDocumentPath);
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;

                //Check if the document have checkouted version 
                businessEntitiesDomainContext.GetLastVersion(ListDocument[SelectedDocumentIndex].Identifier,
                    delegate(InvokeOperation<VersioningItem> retr)
                    {
                        if (retr != null && retr.Value != null && retr.Value.IsValid)
                        {
                            var version = retr.Value;
                            if (version.State == NetBay.Core.BusinessEntities.Versioning.VersionState.Checkout)
                            {
                                //document is checkouted!
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", string.Format(Resx.GetLabel(ResxFolderPage.DOCUMENT_IS_IN_CHECKOUT_BY) + " (Version={1})", version.CreatedBy, version.VersionId), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                                L_oMessage.ShowDialog();
                            }
                            else
                            {
                                //ObservableCollection<VersioningItem> Versions = new ObservableCollection<VersioningItem>(ListDocument[SelectedDocumentIndex].AllVersion);
                                NetBay.Core.BusinessEntities.Versioning.VersionType CurrentVersionType = ListDocument[SelectedDocumentIndex].CurrentModelVersion.ModelType;
                                if (CurrentVersionType == NetBay.Core.BusinessEntities.Versioning.VersionType.NoControl)
                                {
                                    //In this mode the version must be overwrite
                                    this._versioningManager.OverwriteVersion(ListDocument[SelectedDocumentIndex].Identifier, new FileInfo(l_sDocumentPath), ListDocument[SelectedDocumentIndex].ImageName);
                                }
                                else
                                {
                                    //Create version with new file
                                    this._versioningManager.AddVersionFromFile(ListDocument[SelectedDocumentIndex].Identifier, new FileInfo(l_sDocumentPath), ListDocument[SelectedDocumentIndex].CurrentModelVersion.Identifier, true);
                                }
                                DownloadDocument(ListDocument[SelectedDocumentIndex]);
                            }
                        }
                    }, null);

            }
            else
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", "L'edition d'un document n'est possible que si le versionning est activé sur le type de dossier", MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.ShowDialog();
            }
        }

        protected void OnCheckInClick()
        {
            if (ListDocument[SelectedDocumentIndex].CurrentModelVersion != null)
            {
                BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                //Check if the document have checkouted version 
                businessEntitiesDomainContext.GetLastVersion(ListDocument[SelectedDocumentIndex].Identifier,
                    delegate(InvokeOperation<VersioningItem> retr)
                    {
                        if (retr != null && retr.Value != null && retr.Value.IsValid)
                        {
                            var version = retr.Value;
                            if (version.OwnerId == GlobalWebContext.CurrentUser.UserId &&
                                    version.State == NetBay.Core.BusinessEntities.Versioning.VersionState.Checkout)
                            {

                                //show add version child window
                                AddDocumentVersionChildWindow addDocumentVersionChildWindow = new AddDocumentVersionChildWindow(ListDocument[SelectedDocumentIndex])
                                {
                                    Versions = new ObservableCollection<VersioningItem>(ListDocument[SelectedDocumentIndex].AllVersion),
                                    CurrentVersionType = ListDocument[SelectedDocumentIndex].CurrentModelVersion.ModelType,
                                };
                                addDocumentVersionChildWindow.Closed += delegate
                                {
                                    if (addDocumentVersionChildWindow.DialogResult == true)
                                    {
                                        SplashScreenManager.Wait(this);
                                        if (addDocumentVersionChildWindow.CurrentVersionType == NetBay.Core.BusinessEntities.Versioning.VersionType.NoControl
                                            && addDocumentVersionChildWindow.SelectedFile != null)
                                        {
                                            //In this mode the version must be overwrite
                                            this._versioningManager.OverwriteVersion(ListDocument[SelectedDocumentIndex].Identifier, addDocumentVersionChildWindow.SelectedFile);
                                        }
                                        else
                                        {
                                            //in all Other mode the version is added with major minor schéma
                                            if (addDocumentVersionChildWindow.UseSelectedFile && addDocumentVersionChildWindow.SelectedFile != null)
                                            {
                                                //Create version with new file
                                                this._versioningManager.AddVersionFromFile(ListDocument[SelectedDocumentIndex].Identifier, addDocumentVersionChildWindow.SelectedFile, ListDocument[SelectedDocumentIndex].CurrentModelVersion.Identifier, addDocumentVersionChildWindow.IsMajor);
                                            }
                                            else
                                            {
                                                //Create version form old version
                                                this._versioningManager.AddVersionFromOldVersion(ListDocument[SelectedDocumentIndex].Identifier, addDocumentVersionChildWindow.SelectedVersion, ListDocument[SelectedDocumentIndex].CurrentModelVersion.Identifier, addDocumentVersionChildWindow.IsMajor);
                                            }
                                        }
                                    }
                                };
                                addDocumentVersionChildWindow.ShowDialog();
                            }

                        }
                        else
                        {
                            if (retr != null && retr.Value != null)
                            {
                                //error
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", retr.Value.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                                L_oMessage.ShowDialog();
                            }
                        }
                    }, null);

            }
            else
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", "La publication d'un document n'est possible que si le versionning est activé sur le type de dossier", MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.ShowDialog();
            }
        }

        #endregion

    }
}
